<template>
  <el-card :body-style="{ 'padding': '0px'}">
    <el-row class="chat-container">
      <!-- 左侧边栏：在线用户和会话列表 -->
      <el-col :span="6" class="left-sidebar">
        <!-- 在线用户列表 -->
        <el-row class="online-users">
          <el-col :span="24">
            <div class="section-title">
              <el-icon>
                <User/>
              </el-icon>
              <span>在线用户</span>
            </div>
            <el-scrollbar height="200px">
              <el-row class="user-list">
                <el-col v-for="user in onlineUsers" :key="user.userId" :span="24">
                  <div class="user-item">
                    <el-avatar :size="32" :src="user.avatar?.url">
                      {{ user.name.charAt(0) }}
                    </el-avatar>
                    <span class="user-name">{{ user.name }}</span>
                    <el-tag effect="light" size="small" type="success">在线</el-tag>
                  </div>
                </el-col>
              </el-row>
            </el-scrollbar>
          </el-col>
        </el-row>

        <!-- 会话列表 -->
        <el-row class="chat-sessions">
          <el-col :span="24">
            <div class="section-title">
              <el-icon>
                <ChatRound/>
              </el-icon>
              <span>会话列表</span>
            </div>
            <el-scrollbar height="calc(100vh - 300px)">
              <el-row class="session-list">
                <el-col
                    v-for="session in sessions"
                    :key="session.id"
                    :span="24"
                >
                  <div
                      :class="['session-item', { active: currentSession?.id === session.id }]"
                      @click="selectSession(session.id)"
                  >
                    <el-badge :hidden="!session.unreadCount" :value="session.unreadCount">
                      <el-avatar :size="40" :src="session.avatar?.url">
                        {{ session.name.charAt(0) }}
                      </el-avatar>
                    </el-badge>
                    <div class="session-info">
                      <div class="session-name">{{ session.name }}</div>
                      <div class="session-last-message">
                        {{ getLastMessagePreview(session) }}
                      </div>
                    </div>
                    <div class="session-time">
                      {{ session.updateTime }}
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-scrollbar>
          </el-col>
        </el-row>
      </el-col>

      <!-- 右侧聊天区域 -->
      <el-col :span="18" class="chat-main">
        <template v-if="currentSession">
          <el-row class="chat-header">
            <el-col :span="24">
              <div class="header-content">
                <span>{{ currentSession.name }}</span>
                <el-button plain size="small" type="danger" @click="deleteSession">
                  删除聊天
                </el-button>
              </div>
            </el-col>
          </el-row>

          <el-row class="chat-messages">
            <el-col :span="24">
              <el-scrollbar ref="messageScrollbarRef" height="calc(100vh - 200px)">
                <div class="message-list">
                  <div
                      v-for="message in currentSession.messageList"
                      :key="message.id"
                      :class="['message-item', { 'message-mine': message.me }]"
                  >
                    <el-avatar :size="36" :src="message.avatar?.url">
                      {{ message.name.charAt(0) }}
                    </el-avatar>
                    <div class="message-content">
                      <div :style="message.me ? 'flex-direction: row-reverse;' : ''" class="message-info">
                        <span class="sender-name">{{ message.name }}</span>
                        <span class="message-time">{{ message.createTime }}</span>
                      </div>

                      <!-- 文本消息 -->
                      <div v-if="message.type === 1" class="message-bubble">
                        {{ message.content }}
                      </div>

                      <!-- 图片消息 -->
                      <div v-else-if="message.type === 2" class="message-bubble image-message">
                        <el-image
                            :preview-src-list="[message.content]"
                            :preview-teleported="true"
                            :src="message.content"
                            class="chat-image"
                            fit="cover"
                            @click="previewImage(message.content)"
                        >
                          <template #error>
                            <div class="image-error">
                              <el-icon>
                                <Picture/>
                              </el-icon>
                              <span>图片加载失败</span>
                            </div>
                          </template>
                        </el-image>
                      </div>
                    </div>
                  </div>
                </div>
              </el-scrollbar>
            </el-col>
          </el-row>

          <el-row class="chat-input">
            <el-col :span="18">
              <el-input
                  v-model="messageContent"
                  :rows="3"
                  placeholder="输入消息..."
                  type="textarea"
                  @keyup.enter.prevent="sendMessage"
              />
            </el-col>
            <el-col :span="6" class="send-button-col">
              <el-button :disabled="!messageContent.trim()" type="primary" @click="sendMessage">
                发送
              </el-button>
              <base-upload
                  ref="uploadRef"
                  :limit="1"
                  accept="image"
                  :show-tip="false"
                  button-text="上传图片"
                  style="margin-left: 5px"
                  type="file"
                  @change="handleUploadImage"
              >
              </base-upload>
            </el-col>
          </el-row>
        </template>

        <el-row v-else class="chat-placeholder">
          <el-col :span="24">
            <el-empty description="选择一个会话开始聊天"/>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" center title="图片预览" width="80%">
      <div class="image-preview-container">
        <el-image :src="previewImageUrl" fit="contain" style="width: 100%; max-height: 70vh;"/>
      </div>
    </el-dialog>
  </el-card>
</template>

<script setup>
import {nextTick, onMounted, ref} from 'vue'
import {ChatRound, Picture, User} from '@element-plus/icons-vue'
import request from '@/utils/request'
import {ElMessage, ElMessageBox} from "element-plus";
import {useStore} from "vuex";
import {WEBSOCKET_URL} from "@/utils/config.js";
import BaseUpload from "@/components/common/BaseUpload.vue";
import {useRoute} from "vue-router";

const onlineUsers = ref([])
const sessions = ref([])
const currentSession = ref(null)
const messageContent = ref('')

// 图片预览相关
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')

const socket = ref(null)
const store = useStore()

const uploadRef = ref(null)
const handleUploadImage = async (file) => {
  await request.post('/chat/send', {
    sessionId: currentSession.value.id,
    content: file.filename,
    type: 2
  })
  uploadRef.value.clearFiles()
  await selectSession(currentSession.value.id)
}

const connectWs = () => {
  socket.value = new WebSocket(`${WEBSOCKET_URL}?token=${store.state.userInfo.token}`);

  socket.value.onopen = () => {
    console.log('WebSocket 已连接');
  };

  socket.value.onmessage = async (event) => {
    console.log('收到消息:', event.data);
    if (event.data === 'notify') {
      await fetchSessions()
      await selectSession(currentSession.value.id)
    }
  };

  socket.value.onerror = (error) => {
    ElMessage.error('链接到服务器失败')
  };

  socket.value.onclose = () => {
    console.log('WebSocket 已关闭');
  };
}

const messageScrollbarRef = ref(null);
const scrollToBottom = () => {
  nextTick(() => {
    const scrollbar = messageScrollbarRef.value
    if (scrollbar) {
      scrollbar.scrollTo({
        top: scrollbar.wrapRef.scrollHeight,
        behavior: 'smooth'
      })
    }
  });
};

const fetchOnlineUsers = async () => {
  onlineUsers.value = await request.get('/chat/listOnlineUsers')
}

const route = useRoute()
const fetchSessions = async () => {
  sessions.value = await request.get('/chat/listAllSessions')
  const id = route.query.id
  if (id) {
    await selectSession(id)
  }
}

const selectSession = async (sessionId) => {
  currentSession.value = await request.get(`/chat/listSession/${sessionId}`)
  await request.post(`/chat/read/${sessionId}`)
  session.unreadCount = 0
  scrollToBottom()
}

const sendMessage = async () => {
  if (!messageContent.value.trim()) return
  await request.post('/chat/send', {
    sessionId: currentSession.value.id,
    content: messageContent.value,
    type: 1
  })
  messageContent.value = ''
  await selectSession(currentSession.value.id)
}

const deleteSession = async () => {
  await ElMessageBox.confirm('确定要删除该聊天吗？', '提示', {
    type: 'warning'
  })

  await request.post(`/chat/deleteSession/${currentSession.value.id}`)
  currentSession.value = null
  await fetchSessions()
}

// 获取最后一条消息的预览文本
const getLastMessagePreview = (session) => {
  const lastMessage = session.messageList[session.messageList.length - 1]
  if (!lastMessage) return '暂无消息'

  if (lastMessage.type === 1) {
    return lastMessage.content
  } else if (lastMessage.type === 2) {
    return '[图片]'
  }
  return '暂无消息'
}

// 预览图片
const previewImage = (imageUrl) => {
  previewImageUrl.value = imageUrl
  imagePreviewVisible.value = true
}

onMounted(() => {
  connectWs()
  fetchOnlineUsers()
  fetchSessions()
})
</script>

<style scoped>
.chat-container {
  height: 100vh;
  background-color: #f5f7fa;
}

.left-sidebar {
  height: 100vh;
  background: white;
  border-right: 1px solid #dcdfe6;
}

.section-title {
  padding: 16px;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
}

.user-list, .session-list {
  padding: 8px;
}

.user-item, .session-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin: 4px 0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.user-item:hover, .session-item:hover {
  background-color: #f5f7fa;
}

.user-name {
  margin-left: 12px;
  margin-right: auto;
}

.session-item {
  position: relative;
}

.session-info {
  margin-left: 12px;
  flex: 1;
  min-width: 0;
}

.session-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.session-last-message {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.session-time {
  font-size: 12px;
  color: #909399;
  position: absolute;
  top: 8px;
  right: 8px;
}

.chat-main {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.chat-header {
  background: white;
  border-bottom: 1px solid #dcdfe6;
}

.header-content {
  padding: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-messages {
  flex: 1;
  background: white;
  padding: 16px;
}

.message-list {
  padding: 16px;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  gap: 12px;
}

.message-mine {
  flex-direction: row-reverse;
}

.message-content {
  max-width: 60%;
}

.message-info {
  gap: 5px;
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.sender-name {
  font-weight: 500;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-bubble {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 12px;
  word-break: break-word;
}

.message-mine .message-bubble {
  background: #409eff;
  color: white;
}

/* 图片消息样式 */
.image-message {
  padding: 4px;
  background: transparent;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.message-mine .image-message {
  background: transparent;
  border-color: #409eff;
}

.chat-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.chat-image:hover {
  transform: scale(1.02);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #909399;
  background: #f5f7fa;
  border-radius: 6px;
  min-height: 100px;
  min-width: 150px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.chat-input {
  padding: 16px;
  background: white;
  border-top: 1px solid #dcdfe6;
}

.send-button-col {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-left: 16px;
}

.chat-placeholder {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
}

.active {
  background-color: #ecf5ff;
}
</style>